<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// 允许上传的文件类型（MIME类型 => 扩展名）
$allowedTypes = [
    'image/png'  => 'png',
    'image/jpeg' => ['jpg', 'jpeg'], // JPEG有两种扩展名
];

// 上传目录配置
$uploadDir = __DIR__.'/banner/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// 处理上传结果
$response = [];

try {
    // 验证上传内容
    if (empty($_FILES)) {
        throw new Exception('没有文件被上传');
    }

    // 遍历所有上传文件
    foreach ($_FILES as $fieldName => $fileArray) {
        // 重组多文件上传数组
        $files = reArrayFiles($fileArray);
        
        foreach ($files as $file) {
            $result = [
                'status'  => 'success',
                'name'    => $file['name'],
                'message' => '',
                'path'    => ''
            ];

            try {
                // 基础验证
                if ($file['error'] !== UPLOAD_ERR_OK) {
                    throw new Exception(getUploadError($file['error']));
                }

                // 安全获取文件名
                $fileName = basename($file['name']);
                $tmpName = $file['tmp_name'];

                // 验证文件类型
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mimeType = $finfo->file($tmpName);
                
                // 查找允许的扩展名
                $allowedExts = [];
                foreach ($allowedTypes as $type => $exts) {
                    if ($mimeType === $type) {
                        $allowedExts = is_array($exts) ? $exts : [$exts];
                        break;
                    }
                }

                if (empty($allowedExts)) {
                    throw new Exception('不允许的文件类型: '.$mimeType);
                }

                // 验证文件扩展名
                $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                if (!in_array($extension, $allowedExts)) {
                    throw new Exception('文件扩展名不匹配');
                }

                // 移动文件到目标位置
                $targetPath = $uploadDir.$fileName;
                if (!move_uploaded_file($tmpName, $targetPath)) {
                    throw new Exception('文件移动失败');
                }

                $result['path'] = 'banner/'.$fileName;
            } catch (Exception $e) {
                $result['status'] = 'error';
                $result['message'] = $e->getMessage();
            }

            $response[] = $result;
        }
    }
} catch (Exception $e) {
    http_response_code(400);
    $response = ['error' => $e->getMessage()];
}

echo json_encode($response);

/**
 * 重组多文件上传数组
 */
function reArrayFiles($file) {
    $arr = [];
    foreach ($file['name'] as $key => $name) {
        $arr[] = [
            'name'     => $name,
            'type'     => $file['type'][$key],
            'tmp_name' => $file['tmp_name'][$key],
            'error'    => $file['error'][$key],
            'size'     => $file['size'][$key]
        ];
    }
    return $arr;
}

/**
 * 获取上传错误信息
 */
function getUploadError($code) {
    $errors = [
        UPLOAD_ERR_INI_SIZE   => '文件大小超过服务器限制',
        UPLOAD_ERR_FORM_SIZE  => '文件大小超过表单限制',
        UPLOAD_ERR_PARTIAL    => '文件只有部分被上传',
        UPLOAD_ERR_NO_FILE    => '没有文件被上传',
        UPLOAD_ERR_NO_TMP_DIR => '找不到临时文件夹',
        UPLOAD_ERR_CANT_WRITE => '文件写入失败',
        UPLOAD_ERR_EXTENSION  => 'PHP扩展阻止了文件上传'
    ];
    return $errors[$code] ?? '未知错误';
}